package com.azusa.xbiao.controller;

import com.azusa.xbiao.entity.Result;
import com.azusa.xbiao.entity.StatusCode;
import com.azusa.xbiao.entity.User;
import com.azusa.xbiao.service.UserService;
import com.azusa.xbiao.utils.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Value("${file.uploadFolder}")
    private String realBasePath;     //文件上传真实路径
    @Value("${file.accessPath}")
    private String accessPath;      //虚拟路径

    @Autowired
    private HttpSession session;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询用户详细信息
     * @param id
     * @return
     */
    @GetMapping("findUserDetail/{id}")
    public Result findUserDetail(@PathVariable("id")Integer id){
        User user = userService.findUserLookById(id);
        return new Result(StatusCode.SUCCESS,user);
    }

    /**
     * 修改用户信息
     * @param id
     * @param user
     * @return
     */
    @PutMapping("updateUser/{id}")
    public Result updateUser(@PathVariable("id")Integer id,@RequestBody User user){
        user.setId(id);
        return new Result(StatusCode.SUCCESS,userService.save(user));
    }

    /**
     * 上传头像
     * @param file
     * @param userId
     * @return
     */
    @RequestMapping("upload/{id}")
    public Result upload(@RequestParam("file") MultipartFile file, @PathVariable("id") int userId, HttpServletRequest request){
        //获取请求地址
        String origin = request.getHeader("Origin");
        //获取文件名
        String oldFileName = file.getOriginalFilename();
        String suffixName = oldFileName.substring(oldFileName.lastIndexOf(".")+1);
        if ("jpg".equals(suffixName) || "gif".equals(suffixName) || "png".equals(suffixName) || "jpeg".equals(suffixName)){ //...一系列判断
            String newFileName = UUID.randomUUID() + "-" + oldFileName;
            // 域名访问的相对路径（通过浏览器访问的链接-虚拟路径）
            String saveToPath = origin + accessPath + "user/";
            // 真实路径，实际储存的路径
            String realPath = realBasePath + "user/";
            // 储存文件的物理路径，使用本地路径储存
            String filepath = realPath + newFileName;
            File path = new File(filepath);
            //目录不存在则创建
            if (!path.getParentFile().exists()){
                path.getParentFile().mkdir();
            }
            try {
                //写入文件
                file.transferTo(path);
                //修改上传的用户其pic记录的文件位置
                User user = userService.findUserLookById(userId);
                user.setPic(saveToPath + newFileName);
                User u = userService.save(user);
                return new Result(StatusCode.SUCCESS,u);
            } catch (Exception e) {
                return new Result(StatusCode.ERROR,"上传失败");
            }
        }else {
            return new Result(StatusCode.ERROR,"上传的文件不是图片格式");
        }
    }

    @PutMapping("updateUserPassword/{id}")
    public Result updateUserPassword(@PathVariable("id")Integer id,@RequestBody Map<String,String> params){
        if (params.containsKey("oldPwd")){
            User user = userService.findUserLookById(id);
            String oldPwd = params.get("oldPwd");
            if (oldPwd.equals(user.getPassword())){
                String newPwd = params.get("newPwd");
                user.setPassword(newPwd);
                //保存用户
                userService.save(user);
                //删除用户缓存数据
                session.removeAttribute("userId");
                redisTemplate.delete("loginUser:"+ id);
                return new Result(StatusCode.SUCCESS);
            }
            return new Result(StatusCode.ERROR,"旧密码输入错误");
        }
        return new Result(StatusCode.ERROR,"服务器繁忙，请稍后再试");
    }

    /**
     * 查询用户收藏的商品
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("findCollect/{pageNum}/{pageSize}")
    public Result findCollect(@PathVariable("pageNum")Integer pageNum,@PathVariable("pageSize")Integer pageSize){
        return new Result(StatusCode.SUCCESS,userService.findCollect(pageNum,pageSize,LoginUserUtil.getId()));
    }
}
